package com.changan.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.changan.dto.UserExcelDTO;
import com.changan.entity.OssEntity;
import com.changan.entity.User;
import com.changan.response.Result;
import com.changan.service.UserService;
import com.changan.vo.LoginVO;
import com.changan.vo.UserAddVO;
import com.changan.vo.UserQueryVO;
import com.changan.vo.UserUpdateVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author NieChangan
 * @since 2025-09-03
 */
@CrossOrigin
@Tag(name = "用户管理", description = "用户管理")
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private OssEntity ossEntity;

    @Operation(summary = "添加用户", description = "添加用户信息")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVO loginVO) {
        String token = userService.login(loginVO);
        User user = null;
        if (token != null) {
            user = this.userService.getOne(new QueryWrapper<User>().eq("phone_number", loginVO.getPhoneNumber()));
        }
        return Result.ok().data("token", token).data("user", user);
    }

    @Operation(summary = "添加用户", description = "添加用户信息")
    @PostMapping("/add")
    public Result add(@RequestBody @Valid UserAddVO userAddVO) {
        User user = userService.add(userAddVO);
        return Result.ok().data("user", user);
    }

    @Operation(summary = "根据用户ID获取用户详情", description = "获取用户详情")
    @GetMapping("/user/{id}")
    public Result user(@PathVariable("id") Long id) {
        User user = userService.getUserById(id);
        return Result.ok().data("user", user);
    }

    @Operation(summary = "分页查询用户数据", description = "分页查询用户数据")
    @PostMapping("/list")
    public Result users(@RequestBody UserQueryVO userQueryVO) {
        Page<User> userPage = userService.users(userQueryVO);
        return Result.ok().data("userPage", userPage);
    }

    @Operation(summary = "修改用户信息", description = "修改用户信息")
    @PutMapping("/modify")
    public Result modify(@RequestBody UserUpdateVO userUpdateVO) {
        User user = userService.modify(userUpdateVO);
        return Result.ok().data("user", user);
    }

    @Operation(summary = "删除用户", description = "删除用户")
    @DeleteMapping("/delete/{id}")
    public Result modify(@PathVariable("id") Long id) {
        Boolean result = userService.delete(id);
        return Result.ok().data("result", result);
    }

    @Operation(summary = "修改状态", description = "修改状态")
    @GetMapping("/status/{id}/{status}")
    public Result modify(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Boolean result = userService.status(id, status);
        return Result.ok().data("result", result);
    }

    /**
     * 导出用户列表Excel（EasyExcel）
     */
    @Operation(summary = "导出用户列表Excel", description = "导出用户列表Excel")
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody UserQueryVO queryVO, HttpServletResponse response) throws IOException {
        // 1. 设置响应头（关键：告诉浏览器是文件下载）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        // 2. 处理文件名（避免中文乱码）
        String fileName = URLEncoder.encode("用户列表_" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");

        // 3. 调用服务层获取筛选后的用户列表
        List<UserExcelDTO> userList = userService.listExportUsers(queryVO);

        // 4. EasyExcel写文件流（直接写入response输出流，无需本地存储）
        EasyExcel.write(response.getOutputStream(), UserExcelDTO.class)
                .sheet("用户列表") // Excel工作表名称
                .doWrite(userList); // 写入数据
    }

    @GetMapping("/test")
    public String test() {
        return userService.test();
    }

}
